package org.openmrs.util;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ws.client.core.WebServiceTemplate;

public class ExternalServiceHandler {
	
	private static final String SERVICE_URL = "http://localhost:8080/xacmlauth/AuthService";
	
	private final static Log LOG = LogFactory.getLog(ExternalServiceHandler.class);
	
	private static final ThreadLocal<ExternalServiceHandler> threadLocal = new ThreadLocal<ExternalServiceHandler>() {
		
		protected ExternalServiceHandler initialValue() {
			return new ExternalServiceHandler();
		}
	};
	
	private ExternalServiceHandler() {
	}
	
	public static ExternalServiceHandler getInstance() {
		return threadLocal.get();
	}
	
	public String callService(String request) throws Exception {
		LOG.info("Calling External Service");
		
		WebServiceTemplate wsTemplate = new WebServiceTemplate();
		
		StreamSource source = new StreamSource(new StringReader(request));
		StringWriter responseWriter = new StringWriter();
		
		StreamResult result = new StreamResult(responseWriter);
		wsTemplate.sendSourceAndReceiveToResult(SERVICE_URL, source, result);
		
		return result.getWriter().toString();
	}
	
}
